import {startsWith} from "./startsWith";

export class EventEmitter {
  private _listeners: any = {};
  private maxListener: number = 120;

  subscribe(eventName, callback): Function {
    let listeners = this._listeners, self = this;
    if (listeners[eventName] && listeners[eventName].length >= this.maxListener) {
      throw console.error('监听器的最大数量是%d,您已超出限制', this.maxListener)
    }
    if (listeners[eventName] instanceof Array) {
      if (listeners[eventName].indexOf(callback) === -1) {
        listeners[eventName].push(callback);
      }
    } else {
      listeners[eventName] = [].concat(callback);
    }

    function unsubscribe() {
      self.removeListener(eventName, callback);
    }

    return unsubscribe;
  }

  /**
   * 订阅一次即销毁
   * @param eventName
   * @param listener
   */
  subscribeOnce(eventName, listener): void {
    let self = this;

    function callback() {
      listener.apply(null, Array.prototype.slice.call(arguments));
      self.removeListener(eventName, callback);
    }

    this.subscribe(eventName, callback)
  }

  publish(event, ...args: any): any {
    let listeners = this._listeners[event];
    if (listeners) {
      args = [event].concat(args);
      if (args.length == 1) {
        args.push({});
      }
      let results = [];
      // deferred
      listeners.forEach(callback => {
        results.push(new Promise((resolve, reject) => {
          args.push(resolve);
          args.push(reject);
          callback.apply(null, args)
        }));
      });
      return results.length == 1 ? results[0] : results;
    }
  }


  removeListener(event, listener): void {
    let listeners = this._listeners;
    let arr = listeners[event] || [];
    let i = arr.indexOf(listener);
    if (i >= 0) {
      listeners[event].splice(i, 1);
    }
  }

  removeAllListener(event): void {
    this._listeners[event] = [];
  }

  listeners(event): void {
    return this._listeners[event];
  }

  setMaxListeners(maxListener: number): void {
    this.maxListener = maxListener;
  }
}
